<template>
  <div class="app-container">
    <!-- 顶部按钮区域开始 -->
    <el-form :model="queryParams" ref="queryForm" inline label-width="68px">
      <el-form-item label="关键词">
        <el-input v-model="queryParams.commodity" placeholder="请输入关键词查询"></el-input>
      </el-form-item>
      <el-form-item label="商品状态">
        <el-select v-model="queryParams.status" placeholder="请选择" @change="getList">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" icon="el-icon-search" size="mini" type="primary">搜索</el-button>
        <el-button @click="addGoods" icon="el-icon-plus" size="mini" type="success">新增</el-button>
        <el-button @click="resetQuery" icon="el-icon-refresh" size="mini">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="goodsData" border :height="tableHeight">
      <el-table-column label="序号" width="55">
        <template slot-scope="scope">
          <div style=" text-align:center;">
            {{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="commodity" show-overflow-tooltip min-width="280px" />
      <!-- <el-table-column label="商品快照" align="center" width="108px" v-if="false">
        <template slot-scope="scope">
          <img class="table-img" :src="scope.row.picture" alt="" srcset="">
        </template>
      </el-table-column> -->
      <el-table-column label="商品状态" align="center" show-overflow-tooltip width="120px">
        <template slot-scope="scope">
          {{scope.row.status | filterStatus}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160px">
        <template slot-scope="scope">
          <el-button-group>
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editGoods(scope.row)"></el-button>
            <el-button size="mini" type="success" icon="el-icon-chat-line-round" @click="seePingJia(scope.row)"></el-button>

            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteGoods(scope.row)"></el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%" @close="dialogCLose">
      <el-form label-position="left" :model="dialogForm" ref="dialogFormRef" label-width="78px">
        <el-form-item label="商品名称">
          <el-input v-model="dialogForm.commodity"></el-input>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input type="textarea" v-model="dialogForm.description" :autosize="{ minRows: 2, maxRows: 3}"></el-input>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="dialogForm.price" @input="judgeVal($event)"> <template slot="append">元</template></el-input>
        </el-form-item>
        <el-form-item label="是否包邮">
          <el-radio-group v-model="dialogForm.isMail" @input="isMailChange($event)">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="包邮价格" v-if="dialogForm.isMail == 0">
          <el-input v-model="dialogForm.mailPrice" @input="judgeVals($event)"> <template slot="append">元</template></el-input>
        </el-form-item>
        <el-form-item label="商品状态">
          <el-radio-group v-model="dialogForm.status">
            <el-radio :label="1">待发布</el-radio>
            <el-radio :label="2">已发布</el-radio>
            <el-radio :label="3">已下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品总数">
          <el-input-number size="small" v-model="dialogForm.total" :step="50"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDialogForm">确 定</el-button>
      </span>
    </el-dialog>

    <el-drawer title="评论列表" :visible.sync="drawervVisible" direction="rtl" @close="drawervClose">
      <div class="remarks-box" v-for="(item,index) in  pingJiaData" :key="index">
        <div class="remarks-user">
          <Avatar icon="person" />
          <span class="remarks-user-name">{{item.username ? item.username:'匿名用户'}}</span>
        </div>
        <div class="remarks-content-box">
          <p>
            <Rate disabled :value="item.star" allow-half class="remarks-star"></Rate>
          </p>
          <p class="remarks-content">{{item.content}}</p>
          <p class="remarks-sub">
            <!-- <span class="remarks-item">{{item.goods}}</span> -->
            <span class="remarks-time">{{item.createTime}}</span>
          </p>
        </div>
        <i class="el-icon-error" @click="deletePingJia(item)"></i>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { merchandiseManagement, editCommodity, listProductst, deleteCommodity, commentList, commentRemove } from "@/api/goodsAdmin"
export default {
  data() {
    return {
      options: [{
        value: 1,
        label: '待发布'
      }, {
        value: 2,
        label: '已发布'
      }, {
        value: 3,
        label: '已下架'
      }],
      tableHeight: 200,
      // 遮罩层
      loading: false,
      dialogTitle: '新增商品信息',
      dialogForm: {
        total: 100,
        isMail: 0,
        mailPrice: 0
      },
      dialogVisible: false,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        commodity: null,
        status: null,
        pageNum: 1,
        pageSize: 10,
      },
      goodsData: [],
      pingJiaData: [],
      drawervVisible: false
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.$nextTick(function () {
      this.tableHeight = window.screen.height - 400
      // 监听窗口大小变化
      let self = this
      window.onresize = function () {
        self.tableHeight = window.screen.height - 400
      }
    })
  },
  filters: {
    filterStatus(val) {
      switch (val + '') {
        case '1':
          return '待发布'
        case '2':
          return '已发布'
        case '3':
          return '已下架'
      }
    }
  },
  methods: {
    judgeVal(value) {
      let val = (value && value.split("")) || [];
      let sNum = val.toString(); //先转换成字符串类型
      if (sNum.indexOf('.') === 0) {//第一位就是 . 
        sNum = '0' + sNum
      }
      sNum = sNum.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
      sNum = sNum.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
      sNum = sNum.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      sNum = sNum.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数
      //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
      if (sNum.indexOf(".") < 0 && sNum !== "") {
        sNum = parseFloat(sNum);
      }
      this.dialogForm.price = sNum;
    },
    judgeVals(value) {
      let val = (value && value.split("")) || [];
      let sNum = val.toString(); //先转换成字符串类型
      if (sNum.indexOf('.') === 0) {//第一位就是 . 
        sNum = '0' + sNum
      }
      sNum = sNum.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
      sNum = sNum.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
      sNum = sNum.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      sNum = sNum.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数
      //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
      if (sNum.indexOf(".") < 0 && sNum !== "") {
        sNum = parseFloat(sNum);
      }
      this.dialogForm.mailPrice = sNum;
    },
    getList() {
      this.loading = true
      merchandiseManagement(this.queryParams).then(res => {
        this.loading = false
        this.goodsData = res.rows
        this.total = res.total
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.commodity = null
      this.queryParams.status = null
      this.getList()
    },
    // 是否包邮
    isMailChange(e) {
      // 0包邮
      this.dialogForm.mailPrice = 0
    },
    addGoods() {
      this.dialogTitle = '新增商品信息',
        this.dialogVisible = true
    },
    editGoods(item) {
      this.dialogForm = JSON.parse(JSON.stringify(item))
      this.dialogTitle = '修改商品信息',
      this.dialogVisible = true
    },
    submitDialogForm() {
      if (this.dialogTitle == '新增商品信息') {
        this.dialogForm.userId = this.$store.state.user.userId
        listProductst(this.dialogForm).then(res => {
          this.$modal.msgSuccess('新增商品信息成功')
          this.dialogVisible = false
          this.getList()
        })
      } else {
        editCommodity(this.dialogForm).then(res => {
          this.$modal.msgSuccess('修改商品信息成功')
          this.dialogVisible = false
          this.getList()
        })
      }
    },
    // 查看评价
    seePingJia(row) {
      commentList({ commodityId: row.id }).then(res => {
        this.pingJiaData = res.data
        if (this.pingJiaData.length > 0) {
          this.drawervVisible = true
        } else {
          this.$modal.alert('暂无评价')
        }
      })
    },
    // 删除商品
    deleteGoods(row) {
      const that = this
      this.$modal.confirm('确认要删除该商品吗？').then(function () {
        deleteCommodity({ id: row.id }).then(res => {
          that.$modal.msgSuccess('删除成功')
          that.getList()
        })
      }).catch(function () { });
    },
    dialogCLose() {
      this.dialogForm = {
        total: 100,
        isMail: 0,
        mailPrice: 0
      }
    },
    drawervClose() {
      this.pingJiaData = []
    },
    deletePingJia(row) {
      this.$modal.confirm('确认要删除此评论吗？').then(function () {
        return commentRemove({id:row.id});
      }).then(() => {
        this.pingJiaData = this.pingJiaData.filter(item => item.id != row.id)
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    }
  }
}
</script>

<style scoped lang="scss">
  .remarks-box {
    position: relative;
    padding: 15px;
    display: flex;
    flex-direction: row;
    border-bottom: 1px #ccc dotted;
    .el-icon-error {
      position: absolute;
      top: 30px;
      transform: translateY(-50%);
      right: 34px;
      font-size: 24px;
      color: #eb5851;
      cursor: pointer;
    }
  }
  .remarks-user {
    width: 120px;
  }
  .remarks-user-name {
    padding-left: 15px;
  }
  .remarks-content-box {
    width: calc(100% - 180px);
  }
  .remarks-star {
    background-color: #fff;
  }
  .remarks-content {
    font-size: 14px;
    color: #232323;
    line-height: 28px;
  }
  .remarks-sub {
    margin-top: 15px;
    color: #ccc;
  }
  .remarks-time {
    /* margin-left: 15px; */
  }
  .remarks-page {
    margin: 15px;
    display: flex;
    justify-content: flex-end;
  }
</style>